import time
from datetime import datetime, timedelta
from collections import OrderedDict
from types import FunctionType

from django.shortcuts import render
from django.http import JsonResponse
from django.db.models import Sum, Count

from web import models
from web.utils.pager import Pagernation
from web.utils.group import get_incomma_value

def qianxing_fw_list(request):
    list_display = [
        get_incomma_value('允许通过数','current_permit_count'),
        get_incomma_value('拒绝通过数','current_deny_count'),
        'create_date',
    ]
    model_class = models.QiAnXingFW
    queryset = model_class.objects.all().order_by('-create_date')

    pager = Pagernation(request, queryset)
    # 1.处理表头
    header_list = []
    if list_display:
        for key_or_func in list_display:
            if isinstance(key_or_func, FunctionType):
                header_list.append(key_or_func(None, True))
            else:
                verbose_name = model_class._meta.get_field(key_or_func).verbose_name
                header_list.append(verbose_name)
    else:
        header_list.append(model_class._meta.model_name)
    # 2.处理表格内容
    data_list = queryset[pager.start:pager.end]
    body_list = []
    for row in data_list:
        tr_list = []
        if list_display:
            for key_or_func in list_display:
                if isinstance(key_or_func, FunctionType):
                    tr_list.append(key_or_func(row, False))
                else:
                    tr_list.append('' if getattr(row, key_or_func) == None else getattr(row, key_or_func))
        else:
            tr_list.append(row)
        body_list.append(tr_list)

    context = {
        'body_list': body_list,
        'header_list': header_list,
        'pager': pager,
    }
    return render(request, 'qianxing_fw_list.html', context)


def get_data_dict(field, value):
    today = datetime.now().date() + timedelta(days=1)
    date_dict = OrderedDict()
    for i in range(0, 30):
        date = today - timedelta(days=i)
        date_dict[date.strftime("%Y-%m-%d")] = [time.mktime(date.timetuple()) * 1000, 0]

    queryset = models.QiAnXingFW.objects.filter(create_date__gt=today - timedelta(days=29)).extra(
        select={'ctime': "DATE_FORMAT(web_qianxingfw.create_date,'%%Y-%%m-%%d')"}).values('ctime').annotate(
        ct=Sum(field))
    for item in queryset:
        date_dict[item['ctime']][1] = item['ct']
    return {'name': value, 'data': list(date_dict.values())}


def qianxing_fw_account_chart(request):
    account_mapping = {'current_permit_count': '允许通过数', 'current_deny_count': '拒绝通过数'}
    data_list = []
    for k, v in account_mapping.items():
        data_list.append(get_data_dict(k, v))
    return JsonResponse({'status': True, 'data': data_list})
